<?php

namespace app\admin\service;

use app\admin\dao\MemberDao;
use app\admin\model\UM as UM;
use app\common\model\Member;
use app\common\model\UserPersonnel;
use app\index\service\MemberTokenService;
use ShidianUtil\Exception\DataNotExistException;
use ShidianUtil\Utils\CheckUtil;
use ShidianUtil\Utils\StringUtil;
use think\exception\ValidateException;

/**
 * Class MemberPhoneService
 * @package app\admin\service
 */
class MemberPhoneService
{
    // dao
    private MemberDao $memberDao;

    public function __construct(MemberDao $memberDao)
    {
        $this->memberDao = $memberDao;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return void
     */
    public function modify(UM $user, int $id, array $params): void
    {
        $phone = $params['phone'];

        $record = $this->updateMemberPhone($id, $phone);

        // 同时修改员工手机号
        if (is_id($record->userPersonnelId)) {
            $userPersonnel = UserPersonnel::where('id', $record->userPersonnelId)->find();
            if ($userPersonnel) {
                $userPersonnel->mobile = $phone;
                $userPersonnel->save();
            }
        }
    }

    public function updateMemberPhone(int $id, $phone)
    {

        if (!CheckUtil::isPhoneNumber($phone)) {
            throw new ValidateException('请输入正确的新手机号');
        }

        $record = Member::field(true)
            ->where('id', $id)
            ->whereIn('status', [0, 1])
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该用户不存在或已被删除');
        }

        if (StringUtil::equals($record->phone, $phone)) {
            throw new ValidateException('手机号相同');
        }

        // 查询手机号是否已被绑定
        $repeat = Member::field(true)
            ->where('phone', $phone)
            ->whereIn('status', [0, 1])
            ->find();
        if ($repeat) {
            throw new ValidateException('手机号' . $phone . '已注册');
        }

        $record->phone = $phone;
        $record->save();

        // 退出登录
        $this->getMemberTokenService()->delete($record->id);

        return $record;
    }

    private function getMemberTokenService(): MemberTokenService
    {
        return app(MemberTokenService::class);
    }
}
